//导入express框架并且创建实例
const express = require('express');
const app = express();

//不使用body-parser去解析,在这里我们使用express内置方法
app.use(express.json());
// false:数组或者字符串;true:任意类型
app.use(express.urlencoded({ extended: true }));

//导入cors并且全局挂载
const cors = require('cors');
app.use(cors());

//导入Multer,用于文件上传
const multer = require('multer');
//使用multer中间件创建了一个文件上传处理器
const upload = multer({dest: './public/upload'});
// 表示接受任何类型的文件上传
app.use(upload.any())
//静态托管,可以直接通过URL访问该目录下的文件
app.use(express.static('./public'));

//导入jwt模块并且全局挂载
const jwtConfig = require('./jwt-config/index.js')
// const {
// 	expressjwt: jwt
// } = require('express-jwt')
// app.use(jwt({
// 	secret:jwtConfig.jwtSecretKey,algorithms:['HS256']
// }).unless({
// 	path:[/^\/api\//]
// }))


//全局挂载处理错误的中间件
app.use((req,res,next)=>{
    res.cc = (err,status=1)=>{
        res.send({
            status,
            message:err instanceof Error ? err.message : err
        })
    }
    next();
})

//导入路由模块
const loginRouter = require('./router/login');
app.use('/api',loginRouter);
const userRouter = require('./router/userinfo');
app.use('/user',userRouter);
const settingRouter = require('./router/setting');
app.use('/setting',settingRouter);
const applyRouter = require('./router/apply');
app.use('/apply',applyRouter);
const messageRouter = require('./router/message');
app.use('/msg',messageRouter);
const depMsgRouter = require('./router/department_msg.js')
app.use('/dm', depMsgRouter)
const loginLogRouter = require('./router/login_log.js')
app.use('/llog', loginLogRouter)
const operationLogRouter = require('./router/operation_log.js')
app.use('/olog', operationLogRouter)
const overviewLogRouter = require('./router/overview.js')
app.use('/ov', overviewLogRouter)
const feedbackRouter = require('./router/feedback.js')
app.use('/feedback', feedbackRouter)


// 对不符合joi规则的情况进行报错
const Joi = require('joi')
app.use((err,req, res, next) => {
    if (err instanceof Joi.ValidationError){
        res.send({
            error: err.details[0].message,
            status: 1,
            message:'输入的数据不符合验证规则'
        })
    }
})

//侦听服务器端口
app.listen(3030,()=>{
    console.log("Server started on port " + 3030);
    console.log('服务器已经重启!!!');
});